package com.molichuxing.services.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.services.business.dto.request.create.EsignAccountBizCreateDto;
import com.molichuxing.services.business.dto.request.create.EsignCompanyBizCreateDto;
import com.molichuxing.services.business.dto.request.create.EsignDealerBizCreateDto;
import com.molichuxing.services.business.service.ContractBizService;
import com.molichuxing.services.business.service.EsignBizService;
import com.molichuxing.services.infrastructure.dto.request.create.EsignAccountCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.EsignCompanyCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.EsignDealerCreateDto;
import com.molichuxing.services.infrastructure.dto.request.modify.EsignAccountModifyDto;
import com.molichuxing.services.infrastructure.dto.request.modify.EsignCompanyModifyDto;
import com.molichuxing.services.infrastructure.dto.request.modify.EsignDealerModifyDto;
import com.molichuxing.services.infrastructure.dto.response.EsignAccountDto;
import com.molichuxing.services.infrastructure.dto.response.EsignCompanyDto;
import com.molichuxing.services.infrastructure.dto.response.EsignDealerDto;
import com.molichuxing.services.infrastructure.service.ContractService;
import com.molichuxing.services.infrastructure.service.EsignAccountService;
import com.molichuxing.services.infrastructure.service.EsignCompanyService;
import com.molichuxing.services.infrastructure.service.EsignDealerService;
import com.molichuxing.services.sdk.ESignLib;
import com.timevale.esign.sdk.tech.bean.AccountProfile;
import com.timevale.esign.sdk.tech.bean.PersonBean;
import com.timevale.esign.sdk.tech.bean.UpdatePersonBean;
import com.timevale.esign.sdk.tech.bean.result.AddAccountResult;
import com.timevale.esign.sdk.tech.bean.result.AddSealResult;
import com.timevale.esign.sdk.tech.bean.result.GetAccountProfileResult;
import com.timevale.esign.sdk.tech.bean.result.Result;
import com.timevale.esign.sdk.tech.impl.constants.LicenseQueryType;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 合同 服务实现类
 * </p>
 *
 * @author zhaopenghui
 * @since 2019-10-09
 */
@Service("esignBizService")
public class EsignBizServiceImpl implements EsignBizService {
    private static final Logger logger = LoggerFactory.getLogger(EsignBizServiceImpl.class);

    @Autowired
    EsignAccountService esignAccountService;
    @Autowired
    EsignCompanyService esignCompanyService;
    @Autowired
    EsignDealerService esignDealerService;

    /**
     * 创建用户生成印章
     *
     * @param esignAccountBizCreateDto
     * @returnWWWW
     */
    public Boolean createEsignAccount(EsignAccountBizCreateDto esignAccountBizCreateDto) throws Exception {
        logger.info("createEsignAccount,生成用户印章入参：" + JSONObject.toJSONString(esignAccountBizCreateDto));

        String idNumber = esignAccountBizCreateDto.getIdNo();

        // 查询e签宝是否存在
        GetAccountProfileResult getAccountProfileResult = ESignLib.getAccountInfoByIdNo(idNumber, LicenseQueryType.MAINLAND);
        String accountId = "";
        if (getAccountProfileResult != null && getAccountProfileResult.getErrCode() == 0) {
            AccountProfile accountInfo = getAccountProfileResult.getAccountInfo();
            accountId = accountInfo.getAccountUid();

            String mobile = esignAccountBizCreateDto.getMobile();
            String name = esignAccountBizCreateDto.getName();
            if (!accountInfo.getMobile().equals(mobile) || !accountInfo.getName().equals(name)) {
                UpdatePersonBean updatePersonBean = new UpdatePersonBean();
                updatePersonBean.setMobile(mobile);
                updatePersonBean.setName(name);
                Result updateResult = ESignLib.updateAccount(accountId, updatePersonBean, null);
                if (updateResult.getErrCode() != 0) {
                    logger.error("【修改用户电子印章失败】返回码：" + updateResult.getErrCode() + " " + updateResult.getMsg());
                    return false;
                }
            }
        } else {
            PersonBean personBean = new PersonBean();
            BeanUtils.copyProperties(esignAccountBizCreateDto, personBean);
            AddAccountResult addAccountResult = ESignLib.addAccount(personBean);
            if (addAccountResult != null && addAccountResult.getErrCode() == 0) {
                accountId = addAccountResult.getAccountId();
            } else {
                logger.error("【创建用户电子印章失败】返回码：" + addAccountResult.getErrCode() + " " + addAccountResult.getMsg()
                        + " " + JSONObject.toJSONString(personBean));
                throw new BizException("创建用户电子印章失败");
            }
        }

        AddSealResult addSealResult = ESignLib.addTemplateSeal(accountId);
        if (addSealResult != null && addSealResult.getErrCode() == 0) {
            String sealData = addSealResult.getSealData();
            createEsignAccount(esignAccountBizCreateDto, accountId, sealData);
            return true;
        } else {
            logger.error("【查询用户电子印章失败】返回码：" + addSealResult.getErrCode() + " " + addSealResult.getMsg() + "," + accountId);
            return false;
        }
    }

    /**
     * 添加印章
     *
     * @param esignAccountBizCreateDto
     * @param accountId
     * @param sealData
     * @return
     * @throws Exception
     */
    private Boolean createEsignAccount(EsignAccountBizCreateDto esignAccountBizCreateDto, String accountId, String sealData) throws Exception {
        String idNo = esignAccountBizCreateDto.getIdNo();
        String mobile = esignAccountBizCreateDto.getMobile();
        EsignAccountDto esignAccountDto = esignAccountService.getEsignByNameAndIdNumber(null, idNo);
        if (null == esignAccountDto) {
            EsignAccountCreateDto esignAccountCreateDto = new EsignAccountCreateDto();
            esignAccountCreateDto.setName(esignAccountBizCreateDto.getName());
            esignAccountCreateDto.setIdNumber(esignAccountBizCreateDto.getIdNo());
            esignAccountCreateDto.setAccountId(accountId);
            esignAccountCreateDto.setSealData(sealData);
            esignAccountCreateDto.setPhoneNumber(mobile);
            esignAccountService.createEsignAccount(esignAccountCreateDto);
        } else {
            EsignAccountModifyDto esignAccountModifyDto = new EsignAccountModifyDto();
            esignAccountModifyDto.setAccountId(accountId);
            esignAccountModifyDto.setPhoneNumber(mobile);
            esignAccountModifyDto.setIdNumber(esignAccountBizCreateDto.getIdNo());
            esignAccountModifyDto.setName(esignAccountBizCreateDto.getName());
            esignAccountModifyDto.setSealData(sealData);
            esignAccountService.modifyEsignAccount(esignAccountModifyDto);
        }
        return true;
    }


    /**
     * 生成经销商印章信息
     */
    @Override
    public Boolean createEsignDealer(EsignDealerBizCreateDto esignDealerBizCreateDto) throws Exception {
        logger.info("createEsignDealer,生成经销商印章入参：" + JSONObject.toJSONString(esignDealerBizCreateDto));

        String horizontalText = esignDealerBizCreateDto.getHorizontalText();
        if (StringUtils.isNoneBlank(horizontalText) && horizontalText.length() > 8) {
            throw new BizException("横向文内容不能超过8个字");
        }

        logger.info("生成经销商印章入参:》》》》》》》》" + JSONObject.toJSONString(esignDealerBizCreateDto));
        AddSealResult addSealResult = ESignLib.createOfficialTemplateSeal(esignDealerBizCreateDto.getUpperChord(),
                horizontalText, esignDealerBizCreateDto.getBottomChord());

        EsignDealerDto esignDealerDto = esignDealerService.getEsignDealerById(esignDealerBizCreateDto.getDealerId());
        if (null == esignDealerDto) {
            EsignDealerCreateDto esignDealerCreateDto = new EsignDealerCreateDto();
            esignDealerCreateDto.setId(esignDealerBizCreateDto.getDealerId());
            esignDealerCreateDto.setDealerName(esignDealerBizCreateDto.getUpperChord());
            esignDealerCreateDto.setSealData(addSealResult.getSealData());
            esignDealerService.createEsignDealer(esignDealerCreateDto);
        } else {
            EsignDealerModifyDto esignDealerModifyDto = new EsignDealerModifyDto();
            esignDealerModifyDto.setDealerName(esignDealerBizCreateDto.getUpperChord());
            esignDealerModifyDto.setSealData(addSealResult.getSealData());
            esignDealerModifyDto.setId(esignDealerDto.getEsignDealerId());
            esignDealerService.modifyEsignDealer(esignDealerModifyDto);
        }
        return true;
    }

    /**
     * 生成资产公司印章并保存
     *
     * @param esignCompanyBizCreateDto
     * @return
     */
    public String createEsignCompany(EsignCompanyBizCreateDto esignCompanyBizCreateDto) throws Exception {
        logger.info("createEsignCompany,生成资产公司印章入参:" + JSONObject.toJSONString(esignCompanyBizCreateDto));
        AddSealResult addSealResult = ESignLib.createOfficialTemplateSeal(esignCompanyBizCreateDto.getUpperChord(),
                esignCompanyBizCreateDto.getHorizontalText(), esignCompanyBizCreateDto.getBottomChord());

        Integer companyId = esignCompanyBizCreateDto.getCompanyId();
        Integer type = esignCompanyBizCreateDto.getType();
        EsignCompanyDto esignCompanyDto = esignCompanyService.getEsignCompanyByCompanyId(companyId, type);
        if (esignCompanyDto == null) {
            EsignCompanyCreateDto esignCompanyCreateDto = new EsignCompanyCreateDto();
            BeanUtils.copyProperties(esignCompanyBizCreateDto, esignCompanyCreateDto);
            esignCompanyCreateDto.setSealData(addSealResult.getSealData());
            esignCompanyService.createEsignCompany(esignCompanyCreateDto);
        } else {
            EsignCompanyModifyDto esignCompanyModifyDto = new EsignCompanyModifyDto();
            BeanUtils.copyProperties(esignCompanyBizCreateDto, esignCompanyModifyDto);
            esignCompanyModifyDto.setSealData(addSealResult.getSealData());
            esignCompanyModifyDto.setCompanyId(companyId);
            esignCompanyService.modifyEsignCompany(esignCompanyModifyDto);
        }

        return addSealResult.getSealData();
    }

    /**
     * 批量添加经销商印章
     *
     * @param list
     * @return
     * @throws Exception
     */
    @Override
    public Boolean createEsignDealer(List<EsignDealerBizCreateDto> list) throws Exception {
        if (null == list || list.size() < 1) {
            throw new BizException("经销商信息为空");
        }

        for (EsignDealerBizCreateDto esignDealerBizCreateDto : list) {
            String horizontalText = esignDealerBizCreateDto.getHorizontalText();
            if (StringUtils.isNoneBlank(horizontalText) && horizontalText.length() > 8) {
                logger.info("经销商" + esignDealerBizCreateDto.getDealerId() + "横向文内容不能超过8个字");
                throw new BizException("横向文内容不能超过8个字");
            }
        }

        for (EsignDealerBizCreateDto esignDealerBizCreateDto : list) {
            logger.info("生成经销商印章入参:》》》》》》》》" + JSONObject.toJSONString(esignDealerBizCreateDto));
            String horizontalText = esignDealerBizCreateDto.getHorizontalText();
            AddSealResult addSealResult = ESignLib.createOfficialTemplateSeal(esignDealerBizCreateDto.getUpperChord(),
                    horizontalText, esignDealerBizCreateDto.getBottomChord());

            EsignDealerDto esignDealerDto = esignDealerService.getEsignDealerById(esignDealerBizCreateDto.getDealerId());
            if (null == esignDealerDto) {
                EsignDealerCreateDto esignDealerCreateDto = new EsignDealerCreateDto();
                esignDealerCreateDto.setId(esignDealerBizCreateDto.getDealerId());
                esignDealerCreateDto.setDealerName(esignDealerBizCreateDto.getUpperChord());
                esignDealerCreateDto.setSealData(addSealResult.getSealData());
                esignDealerService.createEsignDealer(esignDealerCreateDto);
            } else {
                EsignDealerModifyDto esignDealerModifyDto = new EsignDealerModifyDto();
                esignDealerModifyDto.setDealerName(esignDealerBizCreateDto.getUpperChord());
                esignDealerModifyDto.setSealData(addSealResult.getSealData());
                esignDealerModifyDto.setId(esignDealerDto.getEsignDealerId());
                esignDealerService.modifyEsignDealer(esignDealerModifyDto);
            }
        }

        return true;
    }

    /**
     * 批量添加公司印章
     *
     * @param list
     * @return
     * @throws Exception
     */
    @Override
    public Boolean createEsignCompany(List<EsignCompanyBizCreateDto> list) throws Exception {
        if (null == list || list.size() < 1) {
            throw new BizException("资产公司信息为空");
        }

        for (EsignCompanyBizCreateDto esignCompanyBizCreateDto : list) {
            if (null == esignCompanyBizCreateDto) {
                continue;
            }

            createEsignCompany(esignCompanyBizCreateDto);
        }
        return true;
    }

    /**
     * 批量添加用户印章
     *
     * @param list
     * @return
     * @throws Exception
     */
    @Override
    public Boolean createEsignAccount(List<EsignAccountBizCreateDto> list) throws Exception {
        if (null == list || list.size() < 1) {
            throw new BizException("用户信息为空");
        }

        for (EsignAccountBizCreateDto esignAccountBizCreateDto : list) {
            if (null == esignAccountBizCreateDto) {
                continue;
            }

            createEsignAccount(esignAccountBizCreateDto);
        }
        return true;
    }


}
